package com.hq.communication;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 奇数执行完等待偶数线程 偶数执行完等待奇数线程
 * 使用Condition await、signal  方式实现线程之间的等待和唤醒操作
 *
 * @author hq
 */
@SuppressWarnings("all")
public class ConditionOddEven {
    static int i = 0;
    static Lock lock = new ReentrantLock();
    static Condition condition = lock.newCondition();

    public static void conditionOdd() {
        while (i < 10) {
            lock.lock();
            try {
                if (i % 2 == 1) {
                    System.out.println(Thread.currentThread().getName() + ":这是奇数" + i++);
                    //System.out.println("conditionOdd 被唤醒");
                    condition.signal(); //唤醒偶数线程
                } else {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":这不是奇数进行睡眠等待"+i );
                        condition.await(); //不是奇数就等待 偶数线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                System.out.println("释放锁");
                lock.unlock();
            }

        }
    }

    public static void conditionEven() {
        while (i < 10) {
            lock.lock();
            try {
                if (i % 2 == 0) {
                    //System.out.println(Thread.currentThread().getName() + ":这是偶数" + i++);
                    i++;
                    //System.out.println("conditionEven 被唤醒");
                    condition.signal();  //唤醒偶数线程
                } else {
                    try {
                        System.out.println(Thread.currentThread().getName() + ":这不是偶数进行睡眠等待"+i );
                        condition.await(); //不是奇数就等待 偶数线程
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }



}
